<template>
  <div>
    <el-button type="primary" @click="dialogFormVisible=true" :icon="Plus">新增</el-button> &nbsp;&nbsp;
    <el-button type="primary" :icon="Delete">删除</el-button>
  </div>

<!--商品列表-->
<div style="margin-top: 10px;">
  <el-table :data="shoppingData" border style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" />
    <el-table-column prop="shoppingId" label="序号" align="center" />
    <el-table-column prop="shoppingNames" label="商品名称" align="center" />
    <el-table-column prop="productionBatch" label="生产批次" align="center" />
    <el-table-column prop="qgPeriod" label="保质期(天)" align="center" >
      <template v-slot="scope">
        {{ scope.row.qgPeriod }}天
      </template>
    </el-table-column>
    <el-table-column prop="productionLicense" label="生产证许可号" align="center" width="132px" />
    <el-table-column prop="manufacturingEnterprise" label="生产企业" align="center" width="207px" />
    <el-table-column prop="information" label="信息完善度" align="center" >
      <template>
        {{ (7/17*100).toFixed(2) }}%
      </template>
    </el-table-column>
    <el-table-column prop="createdBy" label="创建人" align="center" />
    <el-table-column prop="createdDate" label="创建时间" align="center" width="152px" />
    <el-table-column prop="updatedBy" label="修改人" align="center" />
    <el-table-column label="操作" align="center" width="202px" >
      <template v-slot="scope">
        <el-link type="primary" target="_blank" @click="router.push('Detail?shoppingId='+scope.row.shoppingId)">详情</el-link>&nbsp;
        <el-link type="primary" target="_blank" @click="saveUpdate(scope.row.shoppingId)">修改</el-link>&nbsp;
        <el-link type="primary" target="_blank" >导出溯源码</el-link>&nbsp;
        <el-link type="primary" target="_blank" @click="del(scope.row.shoppingId)" >删除</el-link>
      </template>
    </el-table-column>
  </el-table>
</div>

<!--分页-->
<div>
  <table>
  <thead></thead>
  <tbody>
    <tr>
      <td>
        <el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pageSize" :page-sizes="[3, 5, 7, 9]" :background="true" layout="total,slot, sizes" :total="form.totalCount" prev-text="上一页" next-text="下一页" @size-change="handleSizeChange" @current-change="handleCurrentChange">
          <span>
            ，每页{{ form.pageSize }}条，当前第:{{ form.pageIndex }}/{{ form.pageCount }}页
          </span>
        </el-pagination>
      </td>

      <td>
        <el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pageSize" :page-sizes="[100, 200, 300, 400]" :background="true" layout="slot, prev, pager, next" :total="form.totalCount" prev-text="上一页" next-text="下一页" @size-change="handleSizeChange" @current-change="handleCurrentChange">
          <el-button type="primary" class="btn-prev" @click="handleCurrentChange(1)" :disabled="form.pageIndex==1">首页</el-button>
        </el-pagination>
      </td>

      <td>
        <el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pageSize" :page-sizes="[100, 200, 300, 400]" :background="true" layout="slot, jumper" :total="form.totalCount" prev-text="上一页" next-text="下一页" @size-change="handleSizeChange" @current-change="handleCurrentChange">
          <el-button type="primary" class="btn-prev" @click="handleCurrentChange(form.pageCount)" :disabled="form.pageIndex==form.pageCount">尾页</el-button>
        </el-pagination>
      </td>
    </tr>
  </tbody>
</table>
</div>

<!--表单添加商品-->
<div>
  <el-dialog v-model="dialogFormVisible" title="基本信息" width="500" align-center>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="form" :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>

      <el-form-item label="商品名称" prop="shoppingNameId">
      <el-select v-model="form.shoppingNameId" placeholder="请选择商品名称">
        <el-option v-for="item in shoppingNameData" :key="item.shoppingNameId" :label="item.shoppingNames" :value="item.shoppingNameId" />
      </el-select>
    </el-form-item>

    <el-form-item label="生产批次" prop="productionBatch">
      <el-input v-model="form.productionBatch" />
    </el-form-item>

    <el-form-item label="保质期(天)" prop="qgPeriod">
      <el-input v-model="form.qgPeriod" />
    </el-form-item>

    <el-form-item label="生产许可证号" prop="productionLicense">
      <el-input v-model="form.productionLicense" />
    </el-form-item>

    <el-form-item label="生产企业" prop="manufacturingEnterprise">
      <el-input v-model="form.manufacturingEnterprise" />
    </el-form-item>

    <el-form-item label="封面图" prop="pictureName">
      <el-upload class="avatar-uploader" action="http://localhost:5063/api/PictureManagement/UploadFile" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
    <img v-if="form.pictureName" :src="form.pictureName" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
    </el-form-item>

    <el-form-item style="float:right;">
      <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
</div>

<!--表单修改商品-->
<div>
  <el-dialog v-model="dialogFormVisibleUpdate" title="基本信息" width="500" align-center>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="form" :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>

      <el-form-item label="商品名称" prop="shoppingNameId">
      <el-select v-model="form.shoppingNameId" placeholder="请选择商品名称">
        <el-option v-for="item in shoppingNameData" :key="item.shoppingNameId" :label="item.shoppingNames" :value="item.shoppingNameId" />
      </el-select>
    </el-form-item>

    <el-form-item label="生产批次" prop="productionBatch">
      <el-input v-model="form.productionBatch" />
    </el-form-item>

    <el-form-item label="保质期(天)" prop="qgPeriod">
      <el-input v-model="form.qgPeriod" />
    </el-form-item>

    <el-form-item label="生产许可证号" prop="productionLicense">
      <el-input v-model="form.productionLicense" />
    </el-form-item>

    <el-form-item label="生产企业" prop="manufacturingEnterprise">
      <el-input v-model="form.manufacturingEnterprise" />
    </el-form-item>

    <el-form-item label="封面图" prop="pictureName">
      <el-upload class="avatar-uploader" action="http://localhost:5063/api/PictureManagement/UploadFile" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
    <img v-if="form.pictureName" :src="form.pictureName" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
    </el-form-item>

    <el-form-item style="float:right;">
      <el-button type="primary" @click="submitFormUpdate(ruleFormRef)">保存</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
</div>

</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue'
import axios from 'axios';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Edit, Search, Share, Upload,Plus } from '@element-plus/icons-vue'
import {useRoute,useRouter} from 'vue-router'
import type { UploadProps } from 'element-plus'

const route = useRoute();
const router = useRouter();

//对话框
//添加的对话框
const dialogFormVisible = ref(false)
//修改的对话框
const dialogFormVisibleUpdate = ref(false)

//表单校验
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()

onMounted(() => {
  getShopping()
  getShoppingName()
})

const form: any = reactive({
  shoppingNameId: '',
  productionBatch: '',
  qgPeriod: '',
  productionLicense: '',
  manufacturingEnterprise: '',
  pictureId: '',
  pictureName: '',
  pageIndex: 1,
  pageSize: 5,
  shoppingId: '',
  createdBy: '',
  createdDate: '',
  deletedBy: '',
  deletedDate: '',
  updatedBy: '',
  updateDate: '',
  isDeleted: '',
})

const handleSelectionChange = (val:any) => {
  console.log(val);
}

//图片上传
const handleAvatarSuccess = (picUrl: any) => {
  console.log(picUrl);
  
  form.pictureName = picUrl.data;
} 
//上传前判断(文件类型、文件大小)
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/gif' && rawFile.type !== 'image/png') {
    ElMessage.error('文件格式必须是[JPG,GIF,PNG]格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('文件大小不能超过2MB!')
    return false
  }
  return true
}

//分页
const handleSizeChange = (val: number) => {
  form.pageSize = val;
  getShopping()
}
const handleCurrentChange = (val: number) => {
  form.pageIndex = val;
  getShopping()
}

//商品列表
const shoppingData:any=ref([])
const getShopping = () => {
  let shopping = {
    pageIndex: form.pageIndex,
    pageSize: form.pageSize,
  }
  axios.post('/api/ShoppingManagement/GetShoppingList',shopping).then(res=>{
    console.log(res);
    shoppingData.value = res.data.data.list;
    form.pageCount = res.data.data.pageCount;
    form.totalCount = res.data.data.totalCount;
  }).catch(err=>{
    console.log(err);
    
  })    
}

//商品名称列表
const shoppingNameData:any=ref([])
const getShoppingName=()=>{
  axios.post('/api/ShoppingNameManagement/GetShoppingNameList',{}).then(res=>{
    console.log(res);
    shoppingNameData.value = res.data.data;
  }).catch(err=>{
    console.log(err);
    
  })    
}

//校验
const rules = reactive<FormRules>({
  shoppingNameId: [
    { required: true, message: '请选择商品名称', trigger: 'change',},
  ],
  productionBatch: [
    { required: true, message: '请输入生产批次', trigger: 'blur' },
  ],
  qgPeriod: [
    { required: true, message: '请输入保质期', trigger: 'blur' },
  ],
  productionLicense: [
    { required: true, message: '请输入生产许可证号', trigger: 'blur' },
  ],
  manufacturingEnterprise: [
    { required: true, message: '请输入生产企业', trigger: 'blur' },
  ],
  pictureName: [
    { required: true, message: '请选择封面图', trigger: 'blur' },
  ],
})

//保存
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let shopping ={
        productionBatch:form.productionBatch,
        qgPeriod:form.qgPeriod,
        productionLicense:form.productionLicense,
        manufacturingEnterprise: form.manufacturingEnterprise,      
        shoppingNameId:form.shoppingNameId,
        pictureName:form.pictureName,
        createdBy: localStorage.userName,
        createDate: Date.now
      }
      axios.post('/api/ShoppingManagement/AddShopping',shopping).then(res => {
        console.log(res);
        if (res.data.code == 1) {
          ElMessage.success("保存成功!")
          //关闭对话框
          dialogFormVisible.value=false
          //清除数据
          //form.shoppingName=''
          //刷新页面
          getShopping()
        } 
        if (res.data.code == -2) {
          ElMessage.error("该商品名称已存在,请勿重复操作")
          return
        }
        if (res.data.code == -1) {
          ElMessage.error("保存失败!")
          return
        }
      }).catch(err => {
        console.log(err);
        
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//反填
const saveUpdate = (shoppingId: number) => {
  dialogFormVisibleUpdate.value = true;
  let Backshopping = {
    shoppingId:shoppingId
  }
  axios.post('api/ShoppingManagement/BackInfoShopping',Backshopping).then(res => {
    console.log(res);
    let back = res.data.data;
    form.shoppingId = back.shoppingId;
    form.shoppingNameId=back.shoppingNameId;
    form.productionBatch=back.productionBatch;
    form.qgPeriod=back.qgPeriod;
    form.productionLicense=back.productionLicense;
    form.manufacturingEnterprise = back.manufacturingEnterprise;
    form.pictureId = back.pictureId;
    form.pictureName = back.pictureName;   
    form.createdBy = back.createdBy;
    form.createdDate = back.createdDate;
    form.deletedBy = back.deletedBy;
    form.deletedDate = back.deletedDate;
    form.updatedBy = localStorage.userName;
    form.updateDate=Date.now;
    form.isDeleted=back.isDeleted
  }).catch(err => {
    console.log(err);

  })
}

//修改
const submitFormUpdate = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let updateShopping = {
        shoppingId:form.shoppingId,
        shoppingNameId:form.shoppingNameId,
        productionBatch:form.productionBatch,
        qgPeriod:form.qgPeriod,
        productionLicense:form.productionLicense,
        manufacturingEnterprise: form.manufacturingEnterprise,
        pictureId:form.pictureId,
        pictureName: form.pictureName,
        createdBy: form.createdBy,
        createdDate: form.createdDate,
        deletedBy: form.deletedBy,
        deletedDate:form.deletedDate,
        updatedBy: localStorage.userName,
        updateDate: Date.now,
        isDeleted:form.isDeleted
      }
      console.log(updateShopping.pictureName);
      
      axios.post('/api/ShoppingManagement/UpdateShopping',updateShopping).then(res => {
        console.log(res);
        if (res.data.code == 1) {
          ElMessage.success("保存成功!")
          //关闭对话框
          dialogFormVisibleUpdate.value=false
          //清除数据
          form.shoppingName=''
          //刷新页面
          getShopping()
        } 
        // if (res.data.code == -2) {
        //   ElMessage.error("该商品名称已存在,请勿重复操作")
        //   return
        // }
        if (res.data.code == -1) {
          ElMessage.error("保存失败!")
          return
        }
      }).catch(err => {
        console.log(err);
        
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//删除
const del = (shoppingId: number) => {
  ElMessageBox.confirm(
    '确认删除该溯源商品?',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    }
  )
    .then(() => {
      let delShopping = {
        shoppingId: shoppingId,
        userName:localStorage.userName
      }
      axios.post('/api/ShoppingManagement/DeletedShopping',delShopping).then(res => {
        console.log(res);
        if (res.data.code >= 0) {
          ElMessage.success("删除成功!")
          //刷新页面
          getShopping()
        } else {
          ElMessage.error("删除失败!")
          return
        }
      }).catch(err => {
        console.log(err);

      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}

</script>

<style scoped>

/* 图片上传 */
.avatar-uploader .avatar {
  width: 150px;
  height: 150px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
}

</style>